package com.codemart.lanze.modules.admin;

import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.codemart.lanze.common.annotation.OperationLog;
import com.codemart.lanze.common.base.controller.AdminBaseController;
import com.codemart.lanze.common.security.token.FormToken;
import com.codemart.lanze.common.validator.group.Create;
import com.codemart.lanze.common.validator.group.Update;
import com.codemart.lanze.modules.cms.entity.Category;
import com.codemart.lanze.modules.cms.service.ICategoryService;
import com.codemart.lanze.modules.sys.vo.TreeNode;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 产品分类
 * @Author: lanze
 * @Date: 2019-09-13
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "产品分类")
@Controller
@RequestMapping("/admin/category")
public class CategoryController extends AdminBaseController {

	@Autowired
	private ICategoryService categoryService;

	private static final String BASE_PATH = "admin/category/";

	/**
	 * 分页查询产品分类列表
	 *
	 * @param pageNum
	 *            当前页码
	 * @param name
	 *            产品分类-查询关键字
	 * @param startTime
	 *            开始时间
	 * @param endTime
	 *            结束时间
	 * @param modelMap
	 * @return
	 */
	@RequiresPermissions("category:list")
	@GetMapping
	public String toList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, String searchKey,
			String startTime, String endTime, ModelMap modelMap) throws Exception {
		try {
			log.debug("分页查询产品分类列表参数! pageNum = {}, searchKey = {},  startTime = {}, endTime = {}", pageNum, searchKey,
					startTime, endTime);

			QueryWrapper<Category> ew = new QueryWrapper<>();
			IPage<Category> iPage = categoryService.page(new Page<>(pageNum, PAGESIZE), ew);

			log.info("分页查询产品分类列表结果！ pageInfo = {}", iPage);

			modelMap.put("pageInfo", iPage);
			modelMap.put("name", searchKey);
			modelMap.put("startTime", startTime);
			modelMap.put("endTime", endTime);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return BASE_PATH + "category-list";
	}

	/**
	 * 查询产品分类列表
	 *
	 * @return
	 */
	@RequiresPermissions("category:list")
	@ResponseBody
	@GetMapping("/list")
	public List<Category> list(String searchKey) {
		return categoryService.findListByName(searchKey);
	}

	/**
	 * 根据主键ID删除产品分类
	 *
	 * @param id
	 * @return
	 */
	@OperationLog(value = "删除产品分类")
	@RequiresPermissions("category:delete")
	@DeleteMapping(value = "/category/{id}")
	public ResponseEntity<String> delete(@PathVariable("id") Long id) {
		log.debug("删除产品分类! id = {}", id);

		Category category = categoryService.getById(id);
		if (null == category) {
			log.info("删除的产品分类不存在! id = {}", id);
			return ResponseEntity.status(HttpStatus.NOT_FOUND).body("产品分类不存在!");
		}

		categoryService.removeById(id);
		log.info("删除产品分类成功! id = {}", id);
		return ResponseEntity.ok("已删除!");
	}

	/**
	 * 跳转到产品分类添加页面
	 *
	 * @return
	 */
	@FormToken(save = true)
	@RequiresPermissions("category:create")
	@GetMapping(value = "/add")
	public String add(ModelMap modelMap) {
		return BASE_PATH + "category-add";
	}

	/**
	 * 添加产品分类
	 *
	 * @param category
	 * @return
	 */
	@FormToken(remove = true)
	@OperationLog(value = "添加产品分类")
	@RequiresPermissions("category:create")
	@ResponseBody
	@PostMapping
	public ModelMap saveAdvertPosition(@Validated({ Create.class }) Category category) {
		ModelMap messagesMap = new ModelMap();

		log.debug("添加产品分类参数! category = {}", category);

		// 执行保存
		categoryService.save(category);
		log.info("添加产品分类成功! categoryId = {}", category.getId());
		messagesMap.put("status", SUCCESS);
		messagesMap.put("message", "添加成功!");
		return messagesMap;
	}

	/**
	 * 跳转到产品分类编辑页面
	 *
	 * @return
	 */
	@FormToken(save = true)
	@RequiresPermissions("category:update")
	@GetMapping(value = "/edit/{id}")
	public String edit(@PathVariable("id") Long id, ModelMap modelMap) throws Exception {
		log.debug("跳转到编辑产品分类信息页面参数! id = {}", id);
		Category category = categoryService.getById(id);

		log.info("跳转到编辑产品分类信息页面成功!, id = {}", id);
		modelMap.put("model", category);
		return BASE_PATH + "category-edit";
	}

	/**
	 * 更新产品分类信息
	 *
	 * @param id
	 * @param category
	 * @return
	 */
	@FormToken(remove = true)
	@OperationLog(value = "编辑产品分类")
	@RequiresPermissions("category:update")
	@ResponseBody
	@PutMapping(value = "/{categoryId}")
	public ModelMap updateAdvertPosition(@PathVariable("categoryId") Long categoryId,
			@Validated({ Update.class }) Category category) {
		ModelMap messagesMap = new ModelMap();

		log.debug("编辑产品分类参数! categoryId= {}, category = {}", categoryId, category);

		category.setId(categoryId);
		categoryService.saveOrUpdate(category);
		log.info("编辑产品分类成功! categoryId= {}, category = {}", categoryId, category);
		messagesMap.put("status", SUCCESS);
		messagesMap.put("message", "编辑成功!");
		return messagesMap;
	}

	/**
	 * 检验产品分类名是否存在
	 *
	 * @param id
	 * @param name
	 * @return
	 */
	@ResponseBody
	@GetMapping(value = "/isExist")
	public Boolean isExist(Long id, String name) {
		boolean flag = true;
		log.debug("检验产品分类名称是否存在参数! id= {}, name= {}", id, name);

		Category record = categoryService.findByName(name);
		if (null != record && !record.getId().equals(id)) {
			flag = false;
		}
		log.info("检验产品分类名称是否存在结果! flag = {}", flag);
		return flag;
	}

	/**
	 * 查询内容分类树
	 *
	 * @return
	 */
	@GetMapping("/tree")
	public ResponseEntity<List<TreeNode>> getTreeList() {
		List<TreeNode> treeNodeList = categoryService.findTreeList();
		return ResponseEntity.ok(treeNodeList);
	}

}
